package com.secxiot.consumer.user.controller;

import com.gexin.fastjson.JSONObject;
import com.secxiot.common.constant.ServerStatusEnum;
import com.secxiot.common.entity.ResultVo;
import com.secxiot.common.exception.BaseRuntimeException;
import com.secxiot.common.utils.CachedBeanCopier;
import com.secxiot.common.utils.WXBizDataCrypt;
import com.secxiot.common.utils.WeChatUtil;
import com.secxiot.consumer.narcotic.controller.NarcoticConsumerController;
import com.secxiot.consumer.narcotic.feign.NarcoticClient;
import com.secxiot.consumer.user.feign.UserClient;
import com.secxiot.provider.narcotic.vo.NarcoticPatientInfoVo;
import com.secxiot.provider.user.dto.DeptDto;
import com.secxiot.provider.user.dto.UserDeptDto;
import com.secxiot.provider.user.entity.UserDo;
import com.secxiot.provider.user.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "微信接口")
@RequestMapping("/wx")
@RestController
public class WxController {

    @Autowired
    private UserClient userClient;

    @Autowired
    private NarcoticClient narcoticClient;

    private static final Logger LOG = LoggerFactory.getLogger(NarcoticConsumerController.class);

    @ApiOperation(value = "根据Code获取openId（药品跟踪）", httpMethod = "GET")
    @GetMapping("/narcotic/getOpenIdByCode")
    public ResultVo<Map<String, Object>> getOpenIdByCode(@RequestParam(value = "code", required = true) String code,
                                                         @RequestParam(value = "wxAppId", required = true) String wxAppId) {
        WxAppVo wxApp = userClient.getWxApp(wxAppId);
        if(null== wxApp || wxApp.getStatus() != 1){
            throw new BaseRuntimeException(ServerStatusEnum.APP_NULL);
        }
        Map<String, Object> map = new HashMap<>();
        JSONObject jsonObject = WeChatUtil.getOpenIdByCode(code, wxApp);
        if (jsonObject.get("openid") == null) {
            map.put("errmsg", jsonObject.get("errmsg"));
            map.put("errcode", jsonObject.get("errcode"));
            return new ResultVo<Map<String, Object>>(map);
        }
        String openid = jsonObject.get("openid").toString();

        map.put("openid", openid);
//        map.put("session_key", jsonObject.get("session_key"));
//        map.put("unionid", jsonObject.get("unionid"));
        return new ResultVo<Map<String, Object>>(map);
    }

    @ApiOperation(value = "根据微信Openid获取用户信息(药品跟踪)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "wxOpenid", value = "微信Openid", required = true, paramType = "query", dataType = "String")
    })
    @GetMapping("/narcotic/wxOpenid")
    public ResultVo<UserNarcoticVo> getUserByWxOpenid(@RequestParam(value = "wxOpenid", required = true) String wxOpenid) {
        UserNarcoticVo userNarcoticVo = new UserNarcoticVo();
        List<DeptVo> supperDepts = new ArrayList<>();

        if ("".equals(wxOpenid) || "undefined".equals(wxOpenid)) {
            return new ResultVo<UserNarcoticVo>(ServerStatusEnum.NARCOTIC_WXOPENID);
        }
        UserDo user = userClient.getUserByWxOpenid(wxOpenid);
        if (user == null) {
            throw new BaseRuntimeException(ServerStatusEnum.NOT_FOUND);
        }

        if (null == user.getDeptId() && "0001400002|0001400003|0001400004".contains(user.getType())) {
            throw new BaseRuntimeException(ServerStatusEnum.NO_BIND_DEPT);
        }

        CachedBeanCopier.copy(user, userNarcoticVo);
        userNarcoticVo.setStatus(user.getStatus());
        userNarcoticVo.setSex(user.getSex());
        //获取医院信息
        if (userNarcoticVo.getHospitalId() != null) {
            HospitalVo hospitalVo = userClient.getHospitalById(userNarcoticVo.getHospitalId());
            if (hospitalVo != null) {
                userNarcoticVo.setHospitalAddress(hospitalVo.getAddress());
                userNarcoticVo.setHospitalName(hospitalVo.getHospitalName());
            }
        }
        DeptDto dept = userClient.getDeptByUserId(user.getUserId());
        if (dept != null) {
            userNarcoticVo.setDeptId(dept.getDeptId());
            userNarcoticVo.setDeptName(dept.getName());
        }

        //获取用户部门信息
        List<UserDeptDto> userDeptDtos = userClient.listSupperDeptByUserId(user.getUserId());
        if (!userDeptDtos.isEmpty()) {
            supperDepts = userDeptDtos.stream().map(p -> {
                DeptVo deptVo = new DeptVo();
                CachedBeanCopier.copy(p, deptVo);
                return deptVo;
            }).collect(Collectors.toList());
        }
        userNarcoticVo.setSupperDepts(supperDepts);
        List<NarcoticPatientInfoVo> narcoticPatientInfoVoList = narcoticClient.selectNarcoticPatientInfoList(user.getUserId());

        userNarcoticVo.setIsAuditNarcoticUserInfo(0);
        if (!narcoticPatientInfoVoList.isEmpty()) {
            for (NarcoticPatientInfoVo narcoticPatientInfoVo : narcoticPatientInfoVoList) {
                if (narcoticPatientInfoVo.getIsAudit() == 1) {
                    userNarcoticVo.setIsAuditNarcoticUserInfo(narcoticPatientInfoVo.getIsAudit());
                    userNarcoticVo.setNarcoticUserInfoId(narcoticPatientInfoVo.getPatientInfoId());
                    break;
                }
            }
        }

        userNarcoticVo.setHeaderImg(user.getWxHeadImg());
        return new ResultVo<>(userNarcoticVo);
    }

    @ApiOperation(value = "根据Code获取openId(SOS)", httpMethod = "GET")
    @GetMapping("/sos/getSosOpenIdByCode")
    public ResultVo<Map<String, Object>> getSosOpenIdByCode(@RequestParam(value = "code", required = true) String code,
                                                            @RequestParam(value = "wxAppId", required = true) String wxAppId) {
        WxAppVo wxApp = userClient.getWxApp(wxAppId);
        if(null== wxApp || wxApp.getStatus() != 1){
            throw new BaseRuntimeException(ServerStatusEnum.APP_NULL);
        }
        Map<String, Object> map = new HashMap<>();
        JSONObject jsonObject = WeChatUtil.getOpenIdByCode(code, wxApp);
        if (jsonObject.get("openid") == null) {
            map.put("errmsg", jsonObject.get("errmsg"));
            map.put("errcode", jsonObject.get("errcode"));
            return new ResultVo<Map<String, Object>>(map);
        }
        String openid = jsonObject.get("openid").toString();
        String session_key = jsonObject.get("session_key").toString();
        map.put("openid", openid);
        map.put("hospitalName", wxApp.getHospitalName());
        map.put("session_key", session_key);
        return new ResultVo<Map<String, Object>>(map);
    }

    @ApiOperation(value = "获取微信手机号接口(SOS)", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "encryptedData", value = "用户信息的加密数据", required = true, paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "iv", value = "加密算法的初始向量", required = true, paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "sessionKey", value = "秘钥", required = true, paramType = "form", dataType = "String")
    })
    @PostMapping("/sos/getPhoneNumber")
    public ResultVo<Map<String, Object>> getPhoneNumber(@RequestParam(value = "encryptedData", required = true) String encryptedData,
                                                        @RequestParam(value = "iv", required = true) String iv,
                                                        @RequestParam(value = "sessionKey", required = true) String sessionKey) {
        Map<String, Object> map = new HashMap<>();
        String result = WXBizDataCrypt.decrypt1(encryptedData, sessionKey, iv);
        JSONObject json = JSONObject.parseObject(result);
        if (!StringUtils.isEmpty(result) && result.length() > 0) {
            map.put("purePhoneNumber", json.getString("purePhoneNumber"));
            map.put("phoneNumber", json.getString("phoneNumber"));
            map.put("countryCode", json.getString("countryCode"));
            map.put("msg", "success");
        } else {
            map.put("msg", "解析数据有误");
        }
        return new ResultVo<Map<String, Object>>(map);
    }

    @ApiOperation(value = "根据微信Openid获取用户信息(SOS)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "wxOpenid", value = "微信Openid", required = true, paramType = "query", dataType = "String")
    })
    @GetMapping("/sos/wxOpenid")
    public ResultVo<UserSosVo> getUserBySosWxOpenid(@RequestParam(value = "wxOpenid", required = true) String wxOpenid) {
        UserSosVo userSosVo = new UserSosVo();
        if ("".equals(wxOpenid) || "undefined".equals(wxOpenid)) {
            return new ResultVo<UserSosVo>(ServerStatusEnum.NARCOTIC_WXOPENID);
        }

        UserDo user = userClient.getUserByWxOpenid(wxOpenid);
        if (user == null) {
            return new ResultVo<>(ServerStatusEnum.NOT_DATA_FOUND);
        }

        CachedBeanCopier.copy(user, userSosVo);
        userSosVo.setSex(user.getSex());
        userSosVo.setHeaderImg(user.getWxHeadImg());
        return new ResultVo<>(userSosVo);
    }
}
